package com.coderysh.rabbitmq.model.routing.direct;

import com.coderysh.rabbitmq.util.RabbitmqUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author 姚书恒
 * @version 1.0
 * @email yaoshuheng@zjkeyou.com
 * @date 2021-10-26 14:43:05
 * @description: 消费者No1
 */
public class ConsumerError {
    private static final String EXCHANGE_NAME = "exchange_direct_logs";
    private static final String ROUTING_KEY_INFO = "direct_logs_error";
    private static final String ROUTING_KEY_ERROR = "direct_logs_error";
    private static final String ROUTING_KEY_WARNING = "direct_logs_warning";
    public void consumptionMessage(Channel channel) {
        try {
            // 通道声明指定的交换机，并在交换机不存在时创建交换机
            // 参数1：交换机名称
            // 参数2：交换机类型,direct:路由模型
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String queueName = null;

        try {
            // 交换机绑定队列：临时队列
            queueName = channel.queueDeclare().getQueue();

            // 基于路由key绑定队列和交换机,可以绑定多个
            channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY_ERROR);
            channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY_WARNING);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 消费消息
        // 参数1：消费那个队列的消息
        // 参数2：开启消息的自动确认机制
        // 参数3：消费消息时的回调接口
        try {
            channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
                // 最后一个参数:消息队列中取出的消息
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String routingKey = envelope.getRoutingKey();
                    System.out.println("消费者Error/Warning:[" + routingKey + "]" + new String(body));

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ConsumerError consumerNo1 = new ConsumerError();
        Connection rabbitmqConnection = RabbitmqUtil.connection();
        Channel channel = RabbitmqUtil.createChannel(rabbitmqConnection);
        if (null == channel) {
            return;
        }
        consumerNo1.consumptionMessage(channel);
    }
}
